package com.nightsoul.ehcache.serializer;

import java.nio.ByteBuffer;

import org.ehcache.spi.serialization.Serializer;
import org.ehcache.spi.serialization.SerializerException;

import com.nightsoul.ehcache.bean.Person;

public class PersonSerializer implements Serializer<Person> {

	@Override
	public ByteBuffer serialize(Person object) throws SerializerException {
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		byteBuffer.putInt(object.getAge());
		byteBuffer.put(object.getName().getBytes());
		return ByteBuffer.wrap(byteBuffer.array());
	}

	@Override
	public Person read(ByteBuffer binary) throws ClassNotFoundException, SerializerException {
		int age = binary.getInt();
		String name = new String(binary.array());
		return new Person(name, age);
	}

	@Override
	public boolean equals(Person object, ByteBuffer binary) throws ClassNotFoundException, SerializerException {
		int age = binary.getInt();
		String name = new String(binary.array());
		return age==object.getAge() && name.equals(object.getName());
	}

}
